<template>
  <div class="card">
    <el-tag class="tag" type="danger"> 请注意下订单时的操作只能在推荐列表或药品列表中下单，不能同时在两个列表中下单！ </el-tag>
  </div>
  <!-- 推荐药品界面 -->
  <el-tag class="tag"> 请输入客户描述的症状，我们将为您匹配出符合症状的三种药品供您选择或参考</el-tag>
  <div class="card" style="display: flex;flex-direction: column">
  <el-form class="form">
    <el-form-item>
      <el-input placeholder="请输入症状用于进行药品匹配" style="width: 200px" v-model="data.description"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="loadRecommendList">匹配药品</el-button>
      <el-button type="warning" @click="reset('recommend')">重置</el-button>
      <el-button type="primary" plain style="margin-left: 10px" @click="goToOrder">批量下单</el-button>
    </el-form-item>
  </el-form>
    <el-table :data="data.recommendList" stripe max-height="450px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
      <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
      <el-table-column label="药品图片" fixed="left">
        <template #default="scope">
          <el-image
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              preview-teleported
              style="width: 40px; height: 40px; border-radius: 50%"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="药品价格"></el-table-column>
      <el-table-column prop="unit" label="价格单位"></el-table-column>
<!--      <el-table-column prop="stockQuantity" label="库存数量"></el-table-column>-->
      <el-table-column prop="currentStock" label="当前库存"></el-table-column>
      <el-table-column prop="description" label="药品描述" show-overflow-tooltip width="200"></el-table-column>
      <el-table-column prop="category" label="药品类别" show-overflow-tooltip width="200"></el-table-column>
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleCreateOrder(scope.row)">去下单</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 购买商品列表 -->
  <el-tag class="tag" type="success">这里是药品库，您可在此处搜索到您所需药品</el-tag>
  <div class="card" style="display: flex;flex-direction: column;">
    <div style="margin: 10px 0 10px  100px">
      <el-input placeholder="请输入药品名称进行查询" style="width: 200px" v-model="data.productName"></el-input>
      <el-button type="primary" plain style="margin-left: 10px" @click="loadProductList">查询</el-button>
      <el-button type="warning"  style="margin-left: 10px" @click="reset('product')">重置</el-button>
      <el-button type="primary" plain style="margin-left: 10px" @click="goToOrder">批量下单</el-button>
    </div>
    <div>
      <el-table :data="data.productList" stripe max-height="450px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
        <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
        <el-table-column label="药品图片" fixed="left">
          <template #default="scope">
            <el-image
                :src="scope.row.imageUrl"
                :preview-src-list="[scope.row.imageUrl]"
                preview-teleported
                style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="药品价格"></el-table-column>
        <el-table-column prop="unit" label="价格单位"></el-table-column>
        <el-table-column prop="stockQuantity" label="库存数量"></el-table-column>
        <el-table-column prop="currentStock" label="当前库存"></el-table-column>
        <el-table-column prop="description" label="药品描述" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column prop="category" label="药品类别" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleCreateOrder(scope.row)">去下单</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="pagination">
      <el-pagination
          style="margin-top: 5px"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNum"
          :page-sizes="[3, 5, 10, 15, 20]"
          :page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total">
      </el-pagination>
    </div>
  </div>
<!--下单界面-->
  <el-dialog
      title="下单"
      v-model="orderDialogVisible"
      class="custom-dialog"
  >
    <el-tag type="danger">请注意下单时下单数量如果超出现有库存，则系统会自动将购买数量调整为库存数</el-tag>
  <div class="dialog-content"> <!-- 包裹内容区域 -->
    <el-table :data="data.selectedProducts" stripe class="order-table" >
      <el-table-column prop="productName" label="药品名称" fixed="left"></el-table-column>
      <el-table-column prop="price" label="单价"></el-table-column>
      <el-table-column prop="currentStock" label="现有库存"></el-table-column>
      <el-table-column prop="unit" label="单位"></el-table-column>
      <el-table-column label="购买数量" width="200px">
        <template #default="scope">
          <el-input-number
              v-model="scope.row.quantity"
              :min="1"
              :max="scope.row.currentStock"
              @blur="handleQuantityChange(scope.row)"
          ></el-input-number>
        </template>
      </el-table-column>
      <el-table-column label="总金额" fixed="right">
        <template #default="scope">
          {{ (scope.row.price * scope.row.quantity).toFixed(2) }}
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 20px;">
      <span>订单总金额: {{ totalOrderAmount.toFixed(2) }}</span>
    </div>
    <div style="margin-top: 20px;">
      <el-form>
      <el-form-item label="请选择支付方式">
        <el-select v-model="paymentMethod" placeholder="请选择支付方式">
          <el-option label="微信支付" :value="1"></el-option>
          <el-option label="支付宝支付" :value="2"></el-option>
          <el-option label="现金支付" :value="3"></el-option>
          <el-option label="银行卡支付" :value="4"></el-option>
        </el-select>
      </el-form-item>
      </el-form>
    </div>
  </div>
  <template #footer>
    <el-button @click="orderDialogVisible = false" type="danger">取消</el-button>
    <el-button type="primary" @click="createOrder">生成订单</el-button>
  </template>
  </el-dialog>
</template>
<script setup>
import { loadSellerProductApi } from "@/utils/API/shop/SellerProduct";
import { ElMessage } from "element-plus";
import { reactive, onMounted ,ref} from "vue";
import {createOrderApi, getRecommendListApi, loadSelectProductApi} from "@/utils/API/orders/createOrders";

const data = reactive({
  recommendList: [], // 推荐列表
  productList: [], // 商品数据
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页显示数量
  total: 0, // 总记录数
  productName: '',
  selectedProducts: [], // 选中的商品
  ids: [], // 选中的商品ID
  user: JSON.parse(localStorage.getItem('system-user')||'{}'),
  payStatus: '0',
  description:'',
  rules:{
    paymentMethod:{
      required:true,
      message:'请选择支付方式',
      trigger:'change'
    },
    quantity:{
      required:true,
      message:'请输入购买数量',
      trigger:'blur'
    }
  },
});

const orderDialogVisible = ref(false); // 控制下单对话框的显示
const totalOrderAmount = ref(0); // 订单总金额
const paymentMethod = ref({
  label: '微信支付',
  value: '1'
}); // 支付方式

// 获取推荐列表
const loadRecommendList = () => {
  let params = {
   description:data.description
  };
  // 实现获取推荐列表的逻辑
  getRecommendListApi(params).then(res=>{
    if(res.code==='200'){
      data.recommendList = res.data;
      console.log(res)
    }else{
      ElMessage.error(res.msg)
    }
  })
};

// 获取商品列表
const loadProductList = () => {
  let params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
    productName: data.productName,
  };
  loadSellerProductApi(params).then(res => {
    if (res.code === '200') {
      data.productList = res.data?.list;
      data.total = res.data?.total;
      console.log("data=====", data.productList);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 处理页码改变
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize;
  loadProductList();
};

// 处理页码变化
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum;
  loadProductList();
};

// 处理选中的行
const handleSelectionChange = (rows) => {
  data.selectedProducts = rows.map(v => ({ ...v, quantity: 1 }));
  data.ids = rows.map(v => v.sellerProductId);
};
// 处理选中数据
const handleCreateOrder = (row) => {
  data.selectedProducts = [{ ...row, quantity: 1 }];
  data.ids = [row.sellerProductId];
  goToOrder();
};

// 跳转至下单界面
const goToOrder = () => {
  if (data.selectedProducts.length === 0) {
    ElMessage.warning('请选择至少一个商品');
    return;
  }
  orderDialogVisible.value = true;
  //loadSelectProduct()
  calculateTotal();
};

// 计算订单总金额
const calculateTotal = () => {
  totalOrderAmount.value = data.selectedProducts.reduce((total, product) => {
    return total + product.price * product.quantity;
  }, 0);
};

// 生成订单
const createOrder = () => {
  // 根据支付方式设置订单状态
  const orderStatus = paymentMethod.value === 0 ? '0' : '1'; // 未支付或已支付
  data.payStatus = orderStatus;

  // 订单对象
  const order = {
    orderStatus: orderStatus, // 订单状态：'0' 未支付, '1' 已支付
    userName: data.user.name,  // 当前用户姓名（可以从用户信息中获取）
    totalPrice: totalOrderAmount.value, // 订单总金额
    paymentMethod: paymentMethod.value, // 支付方式
    deletedStatus: '0', // 默认为未删除 '0'
    returnReason: "", // 退货原因（初始为空）
  };

  // 封装订单详情数据
  const orderDetailsList = data.selectedProducts.map((product) => ({
    productId: product.sellerProductId, // 商品ID
    quantity: product.quantity, // 购买数量
  }));

  // 调用 API 创建订单
  createOrderApi({ order, orderDetailsList }).then(res => {
    if (res.code === '200') {
      console.log(res);
      ElMessage.success('下单成功');
      loadProductList()
    } else {
      ElMessage.error(res.msg);
    }
  });

  console.log('生成订单:', order);

  // 关闭下单对话框
  orderDialogVisible.value = false;
};

// 处理购买数量变化
// 处理购买数量变化
const handleQuantityChange = (row) => {
  // 将输入的值转换为数字
  const quantity = Number(row.quantity);

  // 检查输入是否有效
  if (isNaN(quantity) || quantity < 1) {
    ElMessage.warning('请输入有效的购买数量');
    row.quantity = 1; // 重置为最小购买数量
    return;
  }

  // 检查库存是否充足
  if (quantity > row.currentStock) {
    ElMessage.warning('库存不足，已自动调整为最大库存数量');
    row.quantity = row.currentStock; // 将购买数量重置为库存数量
  }

  calculateTotal(); // 重新计算订单总金额
};
// 重置列表
const reset = (op) => {
  switch (op){
    case 'recommend':
      data.description = '';
      data.recommendList = [];
      break;
    case 'product':
      data.productName = '';
      loadProductList();
      break;
  }


};



onMounted(() => {
  loadProductList();
});
</script>

<style scoped>
@import '@/assets/css/tabelContent.css';
.el-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  padding: 12px 0;
}

.el-table td {
  padding: 12px 0;
}

.el-table .el-tag {
  margin: 2px;
}
.card{
  display: flex;
}
.card-item{
  margin-right: 20px;
}
/* 自定义 dialog 样式 */
.custom-dialog {
  max-height: 80vh; /* 设置 dialog 的最大高度为视口的 80% */
  overflow-y: auto; /* 当内容超出时显示滚动条 */
}

/* 包裹内容的区域 */
.dialog-content {
  max-height: 70vh; /* 设置内容区域的最大高度 */
  overflow-y: auto; /* 当内容超出时显示滚动条 */
}

/* 表格样式 */
.order-table {
  width: 100%;
  max-height: 400px; /* 设置表格的最大高度 */
  overflow-y: auto; /* 当表格内容超出时显示滚动条 */
}

.form{
  display: flex;
  flex-direction: row;
  margin-left: 100px;
}
.el-form-item{
  margin-right: 20px;
}
.tag{
  margin:20px 0 20px 0;
  font-size: 16px;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}


</style>